package cn.edu.scau.cmi.chenmiaopeng.controller.compositePattern;
import javafx.stage.Stage;

import javafx.fxml.FXMLLoader;

import java.io.IOException;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.control.ToggleGroup;
import cn.edu.scau.cmi.chenmiaopeng.compositePattern.safePattern.Organization_S;
import cn.edu.scau.cmi.chenmiaopeng.compositePattern.safePattern.Team_S;
import cn.edu.scau.cmi.chenmiaopeng.compositePattern.transparentPattern.Organization_T;  //引入Organization，创建根节点对象
import cn.edu.scau.cmi.chenmiaopeng.compositePattern.transparentPattern.InquiryOrganization;
import cn.edu.scau.cmi.chenmiaopeng.compositePattern.transparentPattern.Team_T;
public class CompositePatternController{
	    @FXML
	    private Button createOrg;

	    @FXML
	    private Button showInfo;

	    @FXML
	    private static RadioButton transparentPattern;

	    @FXML
	    private Button editOrg;

	    @FXML
	    private RadioButton safePattern;

	    @FXML
	    private Label tips;  //static 会使其变成 nullPointer
	    
	    @FXML
	    private  TreeView<String> treeView = new TreeView<String>();
	    private static TreeItem<String> rootTreeItem_S;
	    private static TreeItem<String> rootTreeItem_T;
	    private static TreeItem<String> nowTreeItem=null;    //将其一开始设为空，方便对用户是否点击做判断
	    private static String nowSelectOrg = null;  //当前选择的节点名（为了防止用户没有选择节点，默认操作根节点）
        private static Team_T originalOrg_T;  //透明模式祖结点
        private static Team_S originalOrg_S;  //安全模式祖结点
        public static void setSelectOrgName(String selectOrg){  //这里由监听器去调用
        	nowSelectOrg = selectOrg;
        }
        public static void setOriginalOrganization() {  //安全模式和透明模式都有自己的根节点
        	originalOrg_T = new Team_T();
        	originalOrg_T.setName("orginal organization");
        	Team_T.setOriginalOrg(originalOrg_T);  //给所有的Team变量去添加静态的根节点
        	InquiryOrganization.setOrginalOrg_T(originalOrg_T);  //别忘了给这里添加根节点
        	originalOrg_S = new Team_S();
        	originalOrg_S.setName("orginal organization");
        	Team_S.setOriginalOrg(originalOrg_S);  //给所有的Team变量去添加静态的根节点	
        	InquiryOrganization.setOrginalOrg_S(originalOrg_S); 
        }
        
        public static void setOriginalTreeItem(TreeItem<String> root_s,TreeItem<String> root_t) {
        	rootTreeItem_S = root_s;
        	rootTreeItem_T = root_t;
        }
 
		
        public static Organization_T getOriginalOrganization_T() {
        	return originalOrg_T;
        }
        
        public static Organization_S getOriginalOrganization_S() {
        	System.out.println("当前操作的s根节点为："+originalOrg_S);
        	return originalOrg_S;
        }
        
        private void setInquiryModeType() {  //这个表示在每次点击功能按钮打开窗口时，都要对InquiryOrganization进行根结点的初始化
        	if(safePattern.isSelected()) {  //安全模式
        		InquiryOrganization.setOrginalOrg_S(originalOrg_S);
        	}
        	else {  //透明模式
        		InquiryOrganization.setOrginalOrg_T(originalOrg_T);
        	}
        }
        public static String getNowSelectOrg() {  //外部调用该函数返回当前选择的organization,对用户默认的判断逻辑也包含在这里面
        	if(nowSelectOrg==null) nowSelectOrg=originalOrg_T.getName();
        	return nowSelectOrg;
        }
        public static void setTreeItem(TreeItem<String> selectItem) {
        	nowTreeItem = selectItem;
        }
        public static TreeItem<String> getTreeItem() {  //返回当前的操作节点
        	return nowTreeItem; 
        }
        private void updateView_cc(CreateOrganizationController cc) {  //传入controller 实时对TestView进行更新  TreeView<?> treeView
//        	if(nowTreeItem==null) {
//        		if(safePattern.isSelected()) {
//        			nowTreeItem = rootTreeItem_S;
//        		}
//        		else {
//        			nowTreeItem = rootTreeItem_T;
//        		}
//        	}
        	System.out.println("当前操作的节点为："+nowTreeItem.getValue());
               String[] addItemNames = cc.getAddItemNames();
        		for(String addItemName:addItemNames) {
        			nowTreeItem.getChildren().add(new TreeItem<String>(addItemName));
        		}
//            	if(cc.isAddSuccess()) {
//        	}
        }
        private void updateView_ec(EditOrganizationController ec) {  //更新编辑Organization之后的树
        	if(ec.getIsRemove()!=2) {
        		String removeOrgName = EditOrganizationController.getModifyOrgName();  //这里没有找到
        		TreeItem<String> removeTreeItem=null;  //必定能在nowTreeItem下找到
        		for(int i=0;i<nowTreeItem.getChildren().size();i++) {
    				if(nowTreeItem.getChildren().get(i).getValue().equals(removeOrgName)) {
    					removeTreeItem = nowTreeItem.getChildren().get(i);
    					nowTreeItem.getChildren().remove(i);
    					break;
    				}
    			}
        		if(ec.getIsRemove()==1) {                          //假如用户选择移除
        			if(safePattern.isSelected()) {  //安全模式，将去除节点加入祖结点
            			rootTreeItem_S.getChildren().add(removeTreeItem);
            		}
            		else {  //透明模式，将去除节点加入祖结点
            			rootTreeItem_T.getChildren().add(removeTreeItem);
            		}
        		}
        		
        	}
        	else {
        		if(ec.getUpdateSuccess()) {
        			String oldName = EditOrganizationController.getModifyOrgName();
        			String newName = ec.getUpdateOrgName();
        			for(int i=0;i<nowTreeItem.getChildren().size();i++) {
        				if(nowTreeItem.getChildren().get(i).getValue().equals(oldName)) {
        					nowTreeItem.getChildren().get(i).setValue(newName);
        					break;
        				}
        			}
            	}
            }
        }
	    @FXML
	    void click_ShowInformation(ActionEvent event) {
	    	Team_T.setOriginalOrg((Team_T)originalOrg_T);
	    try {
            Stage showStage = new Stage();
	    	FXMLLoader loader = new FXMLLoader(getClass().getResource("/cn/edu/scau/cmi/chenmiaopeng/ui/compositePattern/showInfo.fxml"));
	    	//设置舞台
	    	ShowInfoController sc = new ShowInfoController();
	    	sc.setStage(showStage);
	    	//设置安全/透明模式
	    	if(safePattern.isSelected()) {
	    		ShowInfoController.setSafeType(true);	
	    	}
	    	else {
	    		ShowInfoController.setSafeType(false);
	    	}
	    	//下面将当前用户选择的组织名传给controller,方便其查询并显示组织信息
//	    	int selectIndex = tips.getText().indexOf("：");
//	    	String select = tips.getText().substring(selectIndex+1);
//	    	sc.setSelectOrg(select);
	    	//sc.clickButton() //即可实现显示窗口即显示信息
	    	
	    	Parent root = loader.load();
            Scene scene = new Scene(root,435,462);
            showStage.setScene(scene);
            
            //初始化显示信息（comboBox）
//	    	initShowInfoStage(loader);
            showStage.showAndWait();
	    }
    	catch(IOException e) {
    		e.printStackTrace();
    	}
	    }

	    @FXML
	    void click_CreateOrg(ActionEvent event) {
	    	CreateOrganizationController cc;
	    	try {
	            Stage createStage = new Stage();
		    	FXMLLoader loader = new FXMLLoader(getClass().getResource("/cn/edu/scau/cmi/chenmiaopeng/ui/compositePattern/createOrganization.fxml"));
		    	Parent root = loader.load();
	            Scene scene = new Scene(root,450,462);
	            createStage.setScene(scene);
	            
	            cc = loader.getController();
	            cc.setStage(createStage);
	          //设置安全/透明模式
		    	if(safePattern.isSelected()) {
		    	  CreateOrganizationController.setSafeType(true);	
		    	}
		    	else {
		    		CreateOrganizationController.setSafeType(false);
		    	}
		    	Label w = (Label)root.lookup("#warning");
//		    	if(!select.isEmpty())  CreateOrganizationController.setNowSelectOrg(select);
		    	//若用户没有选择任意一个节点，则默认nowSelectOrg为null,CreateOrgController里则默认是选择的是根节点
		    	cc.setLabelWarning(w);
		    	//初始化创建组织
		    	initAddView(root);
	            createStage.showAndWait();
	            updateView_cc(cc);  //刷新界面
		    }
	    	catch(IOException e) {
	    		e.printStackTrace();
	    	}
	    }

	    @FXML
	    void click_EditOrg(ActionEvent event) {
	    	EditOrganizationController ec = new EditOrganizationController();
	    	try {
	            Stage editStage = new Stage();
		    	FXMLLoader loader = new FXMLLoader(getClass().getResource("/cn/edu/scau/cmi/chenmiaopeng/ui/compositePattern/editOrganization.fxml"));
		    	Parent root = loader.load();
	            Scene scene = new Scene(root,497,458);
	            ec.setStage(editStage);
	          //设置安全/透明模式
		    	if(safePattern.isSelected()) {
		    	  ec.setSafeType(true);	
		    	}
		    	else {
		    		ec.setSafeType(false);
		    	}
		    	initEditView(root);
	            editStage.setScene(scene);
	            editStage.showAndWait();
		    }
	    	catch(IOException e) {
	    		e.printStackTrace();
	    	}
	    	updateView_ec(ec);
	    }
	    
       void initAddView(Parent root) {
    	   Label tips = (Label)root.lookup("#warning");
    	   Button confirm = (Button)root.lookup("#confirm");
    	  RadioButton selectPerson =  (RadioButton)root.lookup("#createPerson");
    	  RadioButton selectTeam =  (RadioButton)root.lookup("#createTeam");
    	  if(nowSelectOrg==null) {
    		  tips.setText("当前要添加的父节点是："+originalOrg_T.getName());
    	  }
    	  else tips.setText("当前要添加的父节点是："+nowSelectOrg);
    	  InquiryOrganization inquiryOrg = new InquiryOrganization();
    	  if(safePattern.isSelected()) {  //安全模式
    	   if(nowSelectOrg==null) nowSelectOrg = originalOrg_T.getName();  //假如用户一开始没有点击任何组织，则默认进行的添加操作为根节点
   		   Organization_S org = inquiryOrg.getOrganization_S(originalOrg_S, nowSelectOrg);
   		   if(org instanceof Team_S) {  
   			   confirm.setDisable(false);  //可以让团队添加个人，这时添加按钮应该使能
       	   }
   		   else {  //若是安全模式下的个人，则直接将确认框禁用
   			   confirm.setDisable(true);
   			   tips.setText("In the safe type mode, you are not allowed to modify the person!");
   		   }
   	   }
    	  ToggleGroup tg = new ToggleGroup();
    	  selectPerson.setToggleGroup(tg);
    	  selectTeam.setToggleGroup(tg);
    	  selectPerson.setSelected(true);
       }
       void initEditView(Parent root) {
    	   ComboBox combo = (ComboBox)root.lookup("#comobox");  //获得子节点下拉框
    	   ChoiceBox choice = (ChoiceBox)root.lookup("#remove_update");
    	   TextField input = (TextField)root.lookup("#input");
    	   Button confirm = (Button)root.lookup("#confirm");
    	   Label tips = (Label)root.lookup("#tips");
    	   ObservableList observeList_com = FXCollections.observableArrayList();
//    	   String nowSelectOrg = nowTreeItem.getValue();  从这个树节点获取值
    	   InquiryOrganization inquiryOrg = new InquiryOrganization();
    	   if(nowSelectOrg==null) nowSelectOrg = originalOrg_T.getName();  //用户没有选择，则将当前操作节点置为根节点
    	   
//    	   EditOrganizationController.setNowOperateOrg(nowSelectOrg);  //用户有选择的情况下，nowSelectOrg = nowTreeItem.getValue()
    	   if(safePattern.isSelected()) {  //安全模式
    		   Organization_S org = inquiryOrg.getOrganization_S(originalOrg_S, nowSelectOrg);
    		   if(org instanceof Team_S) {  //如果当前选择节点是Team,则将其成员加入combo里去
    			   Team_S org_T = (Team_S)org;
        		  for(int i=0;i<org_T.getOrganizationArrayList().size();i++) {
        			  observeList_com.add(org_T.getOrganizationArrayList().get(i).getName());
        		  }
        		  confirm.setDisable(false);
        	   }
    		   else {  //若是安全模式下的个人，则直接将确认框禁用
    			   confirm.setDisable(true);
    			   tips.setText("In the safe type mode, you are not allowed to modify the person!");
    		   }
    	   }
    	   else {                          //透明模式
    		   Organization_T org = inquiryOrg.getOrganization_T(originalOrg_T, nowSelectOrg);
    		   if(org instanceof Team_T) {  //如果当前选择节点是Team,则将其成员加入combo里去
    			   Team_T org_T = (Team_T)org;
        		  for(int i=0;i<org_T.getOrganizationArrayList().size();i++) {
        			  observeList_com.add(org_T.getOrganizationArrayList().get(i).getName());
        		  }
        	   }
    	   }
    	   combo.setItems(observeList_com);  //设置下拉框的初值
           ObservableList observeList = FXCollections.observableArrayList("remove organization","update organization","delete organization");
    	   choice.setItems(observeList);
    	   choice.getSelectionModel().select(0);
    	   input.setVisible(false);
    	   addChoiceListener(choice,input);
       }
       void addChoiceListener(ChoiceBox choice, TextField t) {
    	   ChangeListener changeListener = new ChangeListener() {

			@Override
			public void changed(ObservableValue observable, Object oldValue, Object newValue) {
				if((String)newValue=="update organization") {
					t.setVisible(true);
				}
				else {
					t.clear();
					t.setVisible(false);
				}
			}
    		   
    	   };
    	   choice.getSelectionModel().selectedItemProperty().addListener(changeListener);
       }
}
